﻿using System;
using System.IO;
using System.Windows.Forms;

namespace AnyToService
{
    public partial class FormMain : Form
    {
        public FormMain()
        {
            InitializeComponent();
        }

        private void FormMain_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = e.Data.GetDataPresent(DataFormats.FileDrop) ? DragDropEffects.Link : DragDropEffects.None;
        }

        private void FormMain_DragDrop(object sender, DragEventArgs e)
        {
            string strFileName = ((System.Array)(e.Data.GetData(DataFormats.FileDrop))).GetValue(0).ToString();
            System.Diagnostics.Debug.WriteLine(strFileName);

            if (Path.GetExtension(strFileName) == ".exe")
            {
                labelExeName.Text = strFileName;
            }
            else
            {
                MessageBox.Show(@"无效程序。");
            }
        }

        private void buttonDoCreate_Click(object sender, System.EventArgs e)
        {
            DoCreate(labelExeName.Text, comboBoxRunMethod.Text, textBoxArguments.Text);
            MakeUninstaller(labelExeName.Text);

            MessageBox.Show(@"Done");
        }

        private void DoCreate(string f, string m, string a)
        {
            string path = Path.GetDirectoryName(f);
            string exeName = Path.GetFileNameWithoutExtension(f);

            ExtractHelper(path);

            ExecCMD("sc", String.Format(@"stop {0}", exeName));
            ExecCMD("sc", String.Format(@"delete {0}", exeName));

            ExecCMD("sc", String.Format(@"create {0} binPath= ""{1}"" start= auto", exeName, path + "\\srvany.exe"));
            ExecCMD("sc", String.Format(@"description {0} ""{0}""", exeName));

            ExecCMD("reg",
                    String.Format(
                        @"add HKLM\SYSTEM\CurrentControlSet\Services\{0}\Parameters /v Application /d ""{1} {2}"" /f",
                        exeName, f, a));
            ExecCMD("reg",
                    String.Format(
                        @"add HKLM\SYSTEM\CurrentControlSet\Services\{0}\Parameters /v AppDirectory /d ""{1}"" /f",
                        exeName, path));

            if (DialogResult.Yes == MessageBox.Show(@"现在运行服务？", "", MessageBoxButtons.YesNo))
            {
                ExecCMD("sc", String.Format(@"start {0}", exeName));
            }
        }

        private void MakeUninstaller(string f)
        {
            string p = Path.GetDirectoryName(f);

            if (File.Exists(f + @"\@delservice.bat")) return;

            try
            {
                using (FileStream fs = File.Create(p + @"\@delservice.bat"))
                {
                    using (var bw = new BinaryWriter(fs))
                    {
                        bw.Write(
                            System.Text.Encoding.ASCII.GetBytes(
                                String.Format("sc stop {0}\r\nsc delete {0}\r\n\r\npause\r\ndel srvany.exe\r\ndel @delservice.bat",
                                              Path.GetFileNameWithoutExtension(f)
                                    )
                                )
                            );
                        bw.Close();
                    }

                    fs.Close();
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }

        private void ExtractHelper(string p)
        {
            if (File.Exists(p + @"\srvany.exe")) return;

            try
            {
                using (FileStream fs = File.Create(p + @"\srvany.exe"))
                {
                    using (var bw = new BinaryWriter(fs))
                    {
                        bw.Write(Properties.Resources.srvany);
                        bw.Close();
                    }

                    fs.Close();
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }

        private static string ExecCMD(string cmd, string arguments)
        {
            var psi = new System.Diagnostics.ProcessStartInfo(cmd, arguments)
                          {
                              CreateNoWindow = true,
                              RedirectStandardOutput = true,
                              UseShellExecute = false,
                          };
            System.Diagnostics.Process p = System.Diagnostics.Process.Start(psi);
            return p.StandardOutput.ReadToEnd();
        }

        private void FormMain_DoubleClick(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                string strFileName = ofd.FileName;
                System.Diagnostics.Debug.WriteLine(strFileName);

                if (Path.GetExtension(strFileName) == ".exe")
                {
                    labelExeName.Text = strFileName;
                }
                else
                {
                    MessageBox.Show(@"无效程序。");
                }
            }
        }
    }
}